<?if(!defined("PROLOG_INCLUDED") || PROLOG_INCLUDED!==true)die();

class Cache {
	public $timeOut = 3600;
	public $arCondition = Array();
	public $enabled = true;
	
	public function __construct($arCondition = Array(), $timeOut = 3600, $enabled = true){
		$this->timeOut = (int)$timeOut;
		$this->arCondition = $arCondition;
		$this->enabled = $enabled;
	}

	public function StartCache() {
		if (!$this->enabled) {
			return true;
		}
		$cacheFile = CACHE_PATH . $this->GetCacheName() . '.php';
		if (file_exists($cacheFile)) {
			$timeOutTime = filemtime($cacheFile) + $this->timeOut;
			if (time() >= $timeOutTime) {
				return true;
			} else {
				return false;
			}
		} else {
			return true;
		}
	}

	public function GetCacheName() {
		return md5(serialize($this->arCondition).$_SERVER['PHP_SELF']);
	}
	
	public function SaveCache($arResult) {
		if (!$this->enabled) {
			return false;
		}
		$cacheFile = CACHE_PATH . $this->GetCacheName() . '.php';
		if (file_exists($cacheFile)) {
			unlink($cacheFile);
		}

		$cacheData = $this->SetCacheData($arResult);

		$fp = fopen($cacheFile, 'w');
		if (!fwrite($fp, $cacheData)) {
			fclose($fp);
			return false;
		}
		fclose($fp);
		return true;
	}

	public function SetCacheData($arResult) {
		return serialize($arResult);
	}

	public function GetCache() {
		$cacheFile = CACHE_PATH . $this->GetCacheName() . '.php';
		if (!file_exists($cacheFile)) {
			return false;
		}
		$fp = fopen($cacheFile, 'r');
		$cachedData = fread($fp, filesize($cacheFile));
		fclose($fp);
		return unserialize($cachedData);
	}

	public static function DeleteOldCache($timeOut) {
		if(is_dir(CACHE_PATH)) {
			if($dir = opendir(CACHE_PATH)) {
				while(false !==($file = readdir($dir))) {
					if(is_file(CACHE_PATH.$file) AND substr($file, strlen($file) - 4, 4) == ".php") {
						$timeOutTime = filemtime(CACHE_PATH.$file) + $timeOut;
						if (time() >= $timeOutTime) {
							unlink(CACHE_PATH.$file);
						}
					}
				}
			}
		} else {
			return false;
		}
	}
}


?>